package clang.ops;

import clang.data.Expression;
import clang.data.VarType;
import clang.data.Variable;

public class Operator implements Expression {

	private int opnum = 0;
	private Expression op1 = null, op2 = null, op3 = null;
	private String opcode;
	
	public Operator(String opcode, Expression op1)
	{
		this.opcode = opcode;
		this.op1 = op1;
		this.opnum = 1;
	}
	
	public Operator(String opcode, Expression op1, Expression op2)
	{
		this.op1 = op1;
		this.op2 = op2;
		this.opcode = opcode;
		this.opnum = 2;
	}
	
	public Operator(String opcode, Expression op1, Expression op2, Expression op3)
	{
		this.op1 = op1;
		this.op2 = op2;
		this.op3 = op3;
		this.opcode = opcode;
		this.opnum = 3;
	}
	
	public Variable perform() throws Exception
	{
		if(opnum == 1)
			return CUnaryOperators.perform(opcode, op1);
		else if(opnum == 2)
			return CBinaryOperators.perform(opcode, op1, op2);
		else
			throw new Exception("Invalid operator and/or operands");
	}

	@Override
	public VarType getType() {
		if(opnum == 1)
			return op1.getType();
		else if(opnum == 2)
			return Variable.maxType(op1.getType(), op2.getType());
		else if(opnum == 3)
			return Variable.maxType(op2.getType(), op3.getType());
		else
			return VarType.VOID;
	}

	@Override
	public Variable calculate() throws Exception {
		return perform();
	}

	@Override
	public void setData(Expression e) throws Exception {
		calculate().setData(e);
	}

	@Override
	public void execute() throws Exception {
		perform();
	}

}
